<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path: '/sys-admin/home' }">
        <i class="el-icon-s-promotion"></i> 后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>添加商品基本信息</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>


    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

      <el-form-item label="商品名称" prop="pName">
        <el-input v-model="ruleForm.pName"></el-input>
      </el-form-item>

      <el-form-item label="价格(元)" prop="price">
        <el-input v-model="ruleForm.price"></el-input>
      </el-form-item>

      <el-form-item label="库存/份" prop="inventory">
        <el-input v-model="ruleForm.inventory"></el-input>
      </el-form-item>

      <el-form-item label="排序优先级" prop="sort">
        <el-input v-model="ruleForm.sort"></el-input>
      </el-form-item>

      <div style="padding: 20px 10px 5px 30px;font-size: 14px">商品详情：</div>

      <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入商品详情介绍（如：质量，成分等）"
          v-model="ruleForm.introduction">
      </el-input>

      <div style="padding: 20px 10px 5px 30px;font-size: 14px">请选择商品类别（必填）：
        <template>
          <el-select v-model="ruleForm.cid" placeholder="请选择商品类别">
            <el-option-group
                required:true
                v-for="group in options"
                :key="group.label"
                :label="group.label">
              <el-option
                  v-for="item in group.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-option-group>
          </el-select>
        </template>
      </div>


      <div style="padding: 20px 10px 5px 30px;font-size: 14px">请上传商品图片（必填）：</div>
      <div style="padding: 20px 10px 5px 30px;font-size: 14px">
      <el-upload
          action="http://localhost:9080/upload"
          name="picFile"
          :limit=1
          accept=".png, .jpg, .jpeg"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-success="handleSuccess"
          :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      </div>






      <div style="margin-left: 160px ">
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </div>


    </el-form>

  </div>

</template>

<script>

export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,


      options: [{
        label: '食品分类',
        options: [{
          value: '生鲜', label: '生鲜'
        }, {
          value: '蔬果', label: '蔬果'
        }, {
          value: '冷藏', label: '冷藏'
        }, {
          value: '粮油', label: '粮油'
        }, {
          value: '零食', label: '零食'
        }, {
          value: '休闲食品', label: '休闲食品'
        }]
      }, {
        label: '百货区',
        options: [{
          value: '日用品', label: '日用品'
        }, {
          value: '健康美容', label: '健康美容'
        }, {
          value: '纸质品', label: '纸质品'
        }, {
          value: '清洁用品', label: '清洁用品'
        }, {
          value: '其他杂货', label: '其他杂货'
        }]
      }, {
        label: '酒水调料区',
        options: [{
          value: '调料', label: '调料'
        }, {
          value: '酒水', label: '酒水'
        }, {
          value: '饮料', label: '饮料'
        }, {
          value: '香烟', label: '香烟'
        }]
      }, {
        label: '文具办公区',
        options: [{
          value: '文具办公用品', label: '文具办公用品'
        }]
      }],


      ruleForm: {
        pName: '',
        price: '',
        inventory: '',
        sort: '',
        introduction: '',
        cid: '',
        url:''
      },
      rules: {
        pName: [
          {required: true, message: '请输入商品名称', trigger: 'blur'},
          {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入商品价格', trigger: 'blur'},
          {pattern: /^(\-)*(\d+)\.(\d\d).*$/, min: 1, max: 5, message: '请输入一个1-99999的两位小数', trigger: 'blur'}
        ],
        inventory: [
          {required: true, message: '请输入商品库存', trigger: 'blur'},
          {pattern: /^[1-9][0-9]*$/, min: 1, max: 5, message: '请输入一个1-99999的整数', trigger: 'blur'}
        ],
        cId: [
          {required: true, message: '请选择商品类别', trigger: 'blur'},
          {min: 1, max: 1, message: '请在下拉框中选择合适的类别', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入排序优先级', trigger: 'blur'},
          {pattern: /^(\d{1}|[1-9]{1}[0-9]{1})$/, message: '请输入1-99之间的数', trigger: 'blur'}
        ],
        value: [{required: true, message: "请选择类别", trigger: "blur"}],
        picFile: [{required: true, message: "请上传文件", trigger: "blur"}]
      }
    };
  },
  methods: {

    handleSuccess(response,file,fileList){
      console.log("当前url="+this.ruleForm.url);


        this.ruleForm.url = file.response;
        console.log(this.ruleForm.url);

    },
    goBack(){
      //返回上一页面
      history.back();
    },
    handleRemove(file,fileList){

      console.log(file,fileList);

      this.ruleForm.url ="";

      let urls = 'http://localhost:9080/remove?url='+file.response;
      console.log("urls=" + urls);
      // let formData = this.qs.stringify(file.response);

      this.axios.get(urls).then((response) => {
        console.log("删除成功！");
      })

    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },


    submitForm(formName) {


      this.$refs[formName].validate((valid) => {
        if (valid) {

          console.log("url="+this.ruleForm.url);
          let urls = 'http://localhost:9080/products/add-new';
          console.log("urls=" + urls);

          let formData = this.qs.stringify(this.ruleForm);
            console.log(formData);
          this.axios.post(urls, formData).then((response) => {

            let jsonResult = response.data;
            console.log(jsonResult);
            if (jsonResult.state == 20000) {

              this.$message({
                message: '添加商品成功！',
                type: "success"
              })

              //!!!

              this.$router.replace('/admin');

            } else {
              this.$alert(jsonResult.message, '操作失败', {
                confirmButtonText: '确定',
                callback: action => {}
              });
          }
          })

        } else {
          this.$alert("请填写完整信息", '操作失败', {
            confirmButtonText: '确定',
            callback: action => {}
          });

        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
}

</script>


